package com.zzmcc.jms.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.render.excel.JxlsRender;
import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.AuthorizeInterceptor;
import com.zzmcc.jms.model.Material;
import util.ChristStringUtil;

import java.util.*;

import static com.zzmcc.jms.common.ModelConfigWms.TABLE_Material;


public class StockRentController extends BaseController {

	@Before(AuthorizeInterceptor.class)
	public void index() {

		StringBuffer whee = new StringBuffer();
		List<Object> param = new ArrayList<Object>();
		String name = getPara("material.name");
		String supplier = getPara("material.supplier");


		if(ChristStringUtil.isNotEmpty(name)){
			whee.append(" and name like ?");
			param.add("%" + name + "%");
		}


		if(ChristStringUtil.isNotEmpty(supplier)){
			whee.append(" and supplier like ?");
			param.add("%" + supplier + "%");
		}

		Page<Material> pager = Material.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 20),
				"select * ",
				" from " + TABLE_Material+" where 1=1 \n"
				+ whee.toString() + " order by createDate desc",
				param.toArray()
			) ;

		setAttr("pager",pager);
		setAttr("name",name);
		setAttr("supplier",supplier);
		render("../stock_rent_list.html");
	}

	public void add() {
		render("../material_input.html");
	}


	public void save() {
		Material s = getModel(Material.class, "material");
		s.set("createDate", new Date());
		s.save();
		renderDWZSuccessJson("添加成功！");
	}
	
	public void edit() {
		setAttr("material",Material.dao.findById(getPara("id")));
		render("../material_input.html");
	}
	
	public void update() {
		Material s = getModel(Material.class, "material");
		s.update();
		renderDWZSuccessJson("消息修改成功！");
	}
	
	public void delete() {
		String[] ids = getParaValues("ids");
		for(String id:ids){
			Material.dao.deleteById(id);
		}
		renderDWZSuccessJson("删除成功!");
	}

	public void export() {

		String sql = "select catalogue,id,name,unit,model,supplier,createDate,memo  from " + TABLE_Material;
		List<Record> mDetail = Db.find(sql);

		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("mDetail", mDetail);

		String templateFileName = PathKit.getRootClassPath() + "/tpl_material.xls";
		String filename = "material.xls";
		render(JxlsRender.me(templateFileName).filename(filename).beans(beans));

	}

}
